package com.example.finalproject;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.util.Log;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

public class DBManger {
    private DBHelper dbHelper;
    private String TBNAME;
    private static final String TAG="dbmanger";
    public DBManger(Context context) {
        dbHelper = new DBHelper(context);
        TBNAME = DBHelper.TB_NAME;
    }
    public void add(HistoryItem item){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("Difficulty", item.getDifficulty());
        values.put("Score", item.getScore());

        Log.i(TAG,"Difficulty_add="+item.getDifficulty());
        Log.i(TAG,"Score_add="+item.getScore());
        db.insert(TBNAME, null, values);
        db.close();
    }
    public void addAll(List<HistoryItem> list){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        for (HistoryItem item : list) {
            ContentValues values = new ContentValues();
            values.put("Difficulty", item.getDifficulty());
            values.put("Score", item.getScore());
            db.insert(TBNAME, null, values);
        }
        db.close();
    }


    public ArrayList<HistoryItem> listAll(){
        ArrayList<HistoryItem> historyList = null;
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(TBNAME, null, null, null, null, null, null);
        if(cursor!=null){
            historyList = new ArrayList<HistoryItem>();
            while(cursor.moveToNext()){
                HistoryItem item = new HistoryItem();
                item.setScore(cursor.getInt(cursor.getColumnIndex("SCORE")));
                item.setDifficulty(cursor.getString(cursor.getColumnIndex("DIFFICULTY")));
                Log.i(TAG,"Difficulty_listall="+item.getDifficulty());
                Log.i(TAG,"Score_listall="+item.getScore());

                historyList.add(item);
            }
            cursor.close();
        }
        db.close();
        return historyList;

    }

//    public HistoryItem findById(int i){
//        SQLiteDatabase db = dbHelper.getReadableDatabase();
//        Cursor cursor = db.query(TBNAME, null, "SCORE=?", new String[]{String.valueOf(score)}, null, null, null);
//        HistoryItem historyItem = null;
//        if(cursor!=null && cursor.moveToFirst()){
//            historyItem = new HistoryItem();
//            historyItem.setScore(cursor.getInt(cursor.getColumnIndex("SCORE")));
//            historyItem.setDifficulty(cursor.getString(cursor.getColumnIndex("DIFFICULTY")));
//            cursor.close();
//        }
//        db.close();
//        return historyItem;
//    }

}
